package com.jiayu.wheel.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiayu.wheel.dao.UserDao;
import com.jiayu.wheel.domain.User;
import com.jiayu.wheel.dto.UserDto;
import com.jiayu.wheel.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 */
@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl {
    @Autowired
    private UserDao userDao;

    @Autowired
    private UserMapper userMapper;

    @Cacheable(key = "#id")
    public UserDto getUserById(int id){
        UserDto userDto = new UserDto();
        User user = userDao.getById(id);
        BeanUtils.copyProperties(user,userDto);
        return userDto;
    }

    public List<UserDto> getUserByName(String name){
        List<User> list = userMapper.queryByName(name);
        if (list == null || list.size() < 1) {
            return null;
        } else {
            List<UserDto> userDtoList = new ArrayList<>();
            for (User user : list) {
                userDtoList.add(new UserDto(user));
            }
            return userDtoList;
        }
    }

    public List<User> queryList(){
        List<User> list = userDao.queryList();
        return list;
    }


    @CachePut(key = "#userDto.id")
    public void add(UserDto userDto){
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setCreateDate(new Date());
        int result = userMapper.insert(user);
        if (result == 1){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }
    }

    @CacheEvict(key = "#id")
    public int deleteById(int id){
        return userMapper.deleteById(id);
    }

    public PageInfo queryByPage(int start, int size){
        PageInfo<UserDto> pageInfo = new PageInfo<>();
        PageHelper.startPage(start,size,"id desc");
        List<User> list = userMapper.queryAll();
        List<UserDto> userDtoList = new ArrayList<>();
        for (User user : list) {
            userDtoList.add(new UserDto(user));
        }
        pageInfo.setList(userDtoList);
        return pageInfo;
    }
}
